<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Support\generate_sign;
use Illuminate\Support\Facades\DB;
use App\Models\UsersWechat;
use App\Models\UserProfile;
use App\Models\Box;
use App\Models\LifeScene;
use App\Models\Comment;
use App\Models\Colour;
use App\Models\occupation;
use App\Models\position;
use App\Models\UserAddress;
use App\Models\BoxAddress;
use App\Models\Feedback;
use App\Models\Activity;
use App\Models\ActivityJoin;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Hash;
use Tymon\JWTAuth\Facades\JWTAuth;
use Validator;

class AccountController extends Controller
{

    public function postAccountInfo(){
        $user = JWTAuth::parseToken()->authenticate();
        $user = UsersWechat::where('id',$user->id)->first();
        $profile =  UserProfile::where('wechat_id',$user->id)->first();
        if ($profile) {
            $profile->color =  unserialize($profile->color);
            $profile->thing = unserialize($profile->thing);
            $profile->photo = url($profile->photo);
        }
        $user->UserAddress = UserAddress::where(['wechat_id'=>$user->id,'default'=>1])->first();
        $box = Box::where('status','<',4)->where('wechat_id',$user->id)->orderBy('status','DESC')->orderBy('delivery_at','ASC')->first();
        $data = compact('user','profile','box');
        return response()->json(['code' => 1,'msg' => 'Success','data' => $data]);
    }


    //创建用户资料
    public function AccountCreate(Request $request){
        $user = JWTAuth::parseToken()->authenticate();
        $n =  UserProfile::where('wechat_id',$user->id)->count('id');
        $Profile =  UserProfile::where('wechat_id',$user->id)->first();
        if (!$Profile) {
            $Profile = new UserProfile;
            $Profile->wechat_id = $user->id;
        }
        $input = [];
        //-------------------------第一页身形大数据----------------------//
        if ($request->exists('sex')) {
            $input['sex'] = $Profile->sex = intval($request->input('sex'));//性别
        }
        if ($request->exists('age')) {
            $input['age'] = $Profile->age = intval($request->input('age'));//年龄
        }
        if ($request->exists('height')) {
            $input['height'] =  $Profile->height = intval($request->input('height'));//cm
        }
        if ($request->exists('weight')) {
            $input['weight'] =  $Profile->weight = intval($request->input('weight'));//kg
        }

        if ($request->exists('jacket_size')) {
            $input['jacket_size'] =  $Profile->jacket_size = safe2($request->input('jacket_size'));//上衣尺码
        }

        if ($request->exists('pants_size')) {
            $input['pants_size'] =  $Profile->pants_size = safe2($request->input('pants_size'));//裤子尺码
        }
        if ($request->exists('shoes_size')) {
            $input['shoes_size'] =  $Profile->shoes_size = safe2($request->input('shoes_size'));//鞋子尺码
        }

        if ($request->exists('skin_color')) {
            $input['skin_color'] =  $Profile->skin_color = safe2($request->input('skin_color'));//肤色
        }

        if ($request->exists('figure')) {
            $input['figure'] =  $Profile->figure = safe2($request->input('figure'));//身形
        }
        //-------------------------第一页END----------------------//

        //-------------------------第二页----------------------//
        if ($request->exists('color')) {
            $input['color'] =  $Profile->color = serialize($request->input('color'));   //颜色喜好
            //格式color['黑色']=['color'=>'#000','type'=>1]  type 1 会穿  2可尝试  3不穿
        }
        //-------------------------第二页END----------------------//
        if ($request->exists('life')) {
            $input['life'] =  $Profile->life = safe2($request->input('life'));   //生活场景
        }
        //-------------------------第三页----------------------//

        //-------------------------第四页----------------------//
        if ($request->exists('photo')) {
            $input['photo'] =  $Profile->photo = str_replace(url('').'/','',safe2($request->input('photo')));   //全身照片  数组
        }
        //-------------------------第四页END----------------------//
        //-------------------------第五页----------------------//
        if ($request->exists('occupation')) {
            $input['occupation'] =  $Profile->occupation = safe2($request->input('occupation'));   //行业
        }
        if ($request->exists('position')) {
            $input['position'] =  $Profile->position = safe2($request->input('position'));   //职位
        }
        if ($request->exists('birthday')) {
            $input['birthday'] =  $Profile->birthday = safe2($request->input('birthday'));   //生日
        }
        if ($request->exists('thing')) {
            $input['thing'] =  $Profile->thing = serialize($request->input('thing'));   //一起完成的事情 多选 数组
        }
        if ($request->exists('other')) {
            $input['other'] =  $Profile->other = safe2($request->input('other'));//其他/特别注意
        }
        //-------------------------第五页END----------------------//
        $Profile->save();
        if ($request->exists('is_synchro') && intval($request->input('is_synchro')) ===1) {
            $input['color'] = array_key_exists('color',$input) ? $input['color']:serialize([]);
            $input['thing'] = array_key_exists('thing',$input) ? $input['thing']:serialize([]);
            Box::where(['wechat_id'=>$user->id,'to_wechat_id'=>0,'status'=>1])->update($input);
        }
        if ($n==0) {
            $input['color'] = array_key_exists('color',$input) ? $input['color']:serialize([]);
            $input['thing'] = array_key_exists('thing',$input) ? $input['thing']:serialize([]);
            Box::where(['wechat_id'=>$user->id,'to_wechat_id'=>0,'status'=>1])->update($input);
        }
        return response()->json(['code' => 1,'msg' => 'Success','data' => $Profile]);
    }





    //用户地址列表
    public function AddressPageRows(Request $request){
        $user = JWTAuth::parseToken()->authenticate();
        $wechat_id = $user->id;
        $rows = UserAddress::where('wechat_id',$wechat_id)->get();
        $data = compact('rows');
        return response()->json(['code' => 1,'msg' => 'Success','data' => $data]);
    }

    //添加地址
    public function CreateAddress(Request $request){
        $user = JWTAuth::parseToken()->authenticate();
        $input = $request->all();
        $validator = Validator::make($input,
            [
                'username' => 'required',
                'province' => 'required',
                'city' => 'required',
                'area' => 'required',
                'address' => 'required',
                'phone' => 'required',
            ],[
                'required' => ':attribute 不能为空.',
                'integer'=>':attribute 必须是数值',
                'regex'=>':attribute 格式不正确',
            ]);
        if ($validator->fails()) {
            $messages = $validator->errors();
            return response()->json(['code' => -1,'msg' => $messages->first(),'data' => '',]);
        }
        if (!isMobile($request->input('phone'))) {
            return response()->json(['code' => -1,'msg' => '手机格式不正确','data' => null]);
        }
        if ($request->has('id')) {
            $id = intval($request->input('id'));
            $userAddress = UserAddress::where(['id'=>$id,'wechat_id'=>$user->id])->first();
            if (!$userAddress) {
                return response()->json(['code' => -1,'msg' => '地址不存在','data' => null]);
            }
        }
        $n = UserAddress::where(['wechat_id'=>$user->id])->count('id');

        $userAddress = new UserAddress;
        $userAddress ->wechat_id= $user->id;
        $userAddress ->username= $request->input('username');
        $userAddress ->province = $request->input('province');
        $userAddress ->city = $request->input('city');
        $userAddress ->area = $request->input('area');
        $userAddress ->address = $request->input('address');
        $userAddress ->phone = $request->input('phone');
        if ($n==0) {
            $userAddress->default = 1;
            $userAddress->save();
        }

        $userAddress->save();
        if ($request->exists('box_ids')) {
            //同步
            $box_ids = explode(',', $request->input('box_ids'));//可填
            foreach ($box_ids as $key => $id) {
                BoxAddress::boxCopyAddress(['wechat_id'=>$user->id,'box_id'=>$id,'user_address_id'=>$userAddress->id,'type'=>'box']);
            }
        }else{
            if ($n==0) {
                //同步
                $boxRows = Box::where('wechat_id',$user->id)->get();
                foreach ($boxRows as $key => $row) {
                    BoxAddress::boxCopyAddress(['wechat_id'=>$user->id,'box_id'=>$row->id,'user_address_id'=>$userAddress->id,'type'=>'box']);
                }
            }
        }
        return response()->json(['code' => 1,'msg' => 'Success','data' => '',]);
    }

    public function editUserAddress(Request $request){
        $user = JWTAuth::parseToken()->authenticate();
        if (!$request->has('id')) {
            return response()->json(['code' => -1,'msg' => 'id不能为空','data' => null]);
        }
        $id = intval($request->input('id'));
        $row = UserAddress::where('wechat_id',$user->id)->find($id);
        if (!$row) {
            return response()->json(['code' => -1,'msg' => '地址不存在','data' => null]);
        }
        if ($request->exists('username')) {
            $row->username = safe2($request->input('username'));
        }
        if ($request->exists('province')) {
            $row->province = safe2($request->input('province'));
        }
        if ($request->exists('city')) {
            $row->city = safe2($request->input('city'));
        }
        if ($request->exists('area')) {
            $row->area = safe2($request->input('area'));
        }
        if ($request->exists('address')) {
            $row->address = safe2($request->input('address'));
        }
        if ($request->exists('phone')) {
            $row->phone = safe2($request->input('phone'));
        }
        if ($request->exists('default')) {
            UserAddress::where('wechat_id',$user->id)->where('id','<>',$id)->update(['default'=>0]);
            $row->default = 1;
        }
        $row->save();
        return response()->json(['code' => 1,'msg' => 'Success','data' => $row]);
    }

    //删除地址
    public function delUserAddress(Request $request){
        $user = JWTAuth::parseToken()->authenticate();
        if (!$request->has('id')) {
            return response()->json(['code' => -1,'msg' => 'id不能为空','data' => null]);
        }
        $id = intval($request->input('id'));
        UserAddress::where('wechat_id',$user->id)->where('id',$id)->delete();
        return response()->json(['code' => 1,'msg' => 'Success','data' => $id]);
    }


    /**
     * 添加评分
     * @author wuyun
     * @date           2018-07-24T17:10:32+0800
     * @param  Request $request                 [description]
     * @return [type]                           [description]
     */
    public function postCreateComment(Request $request){
        $user = JWTAuth::parseToken()->authenticate();
        $wechat_id = $user->id;
        $evaluate = intval($request->input('evaluate',1));
        $score = intval($request->input('score',1));
        $clothing_score = $request->input('clothing_score');
        $comment = new Comment;
        $comment->evaluate= $evaluate;
        $comment->evaluate= $score;
        $comment->clothing_score= serialize($clothing_score);
        $comment->wechat_id = $wechat_id;
        $comment->save();
        return response()->json(['code' => 1,'msg' => 'Success','data' => $comment]);
    }

    /**
     * 添加反馈
     * @author wuyun
     * @date           2018-07-24T17:10:32+0800
     * @param  Request $request                 [description]
     * @return [type]                           [description]
     */
    public function postCreateFeedback(Request $request){
        $user = JWTAuth::parseToken()->authenticate();
        $input = $request->all();
        $validator = Validator::make($input,
            [
                'type' => 'required',
                'content' => 'required',
            ],[
                'type.required'=>'类型不能为空',
                'content.required'=>'内容不能为空',
            ]);
        if ($validator->fails()) {
            $messages = $validator->errors();
            return response()->json(['code' => -1,'msg' => $messages->first(),'data' => '',]);
        }

        $wechat_id = $user->id;
        $type = safe2($request->input('type'));//直接文字放进来
        $content = safe2($request->input('content'));
        $Feedback = new Feedback;
        $Feedback->type= $type;
        $Feedback->content= $content;
        $Feedback->wechat_id = $wechat_id;
        $Feedback->save();
        return response()->json(['code' => 1,'msg' => 'Success','data' => $Feedback]);
    }

    public function postActivityPageRows(Request $request){
        $user = JWTAuth::parseToken()->authenticate();
        $wechat_id = $user->id;
        $join = ActivityJoin::select('activity_id')->where('wechat_id',$wechat_id)->get();
        $idArr = [];
        foreach ($join as $key => $val) {
            array_push($idArr,$val->activity_id);
        }
        $rows = Activity::with('class')->whereIn('id',$idArr)->paginate(15);
        foreach ($rows as $key => $row) {
            $pic1 = unserialize($row->pic1);
            foreach ($pic1 as $k => $pic) {
                $pic1[$k] = url($pic);
            }
            $row->pic1 =$pic1;
            if (strtotime($row->start_time) > time()) {
                $row->statusName = '未开始';
                $row->statusName = 1;
            }else if (strtotime($row->start_time)>time() && strtotime($row->end_time)>time()) {
                $row->statusName = '进行中';
                $row->statusName = 2;
            }else if (strtotime($row->start_time) < time()){
                $row->statusName = '以结束';
                $row->statusName = 3;
            }
        }
        $data = compact('rows');
        return response()->json(['code' => 1,'msg' => 'Success','data' => $data]);
    }


}
